﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Objects.DataClasses;
using Pharmacy.Ultilities;
using Pharmacy.Data.Core;

namespace Pharmacy.Data
{
    public static class EntityObjectExtend
    {
        /// <summary>
        /// Validate EntityObject Based On Defined Metadata
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="results"></param>
        /// <returns></returns>
        public static bool Validate(this EntityObject entity, out List<string> results)
        {
            var metadataAtt = entity.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
            var metaDataClassType = metadataAtt.MetadataClassType;
            var metafields = metaDataClassType.GetFields();
            var objProperties = TypeDescriptor.GetProperties(entity.GetType()).Cast<PropertyDescriptor>();
            results = (from metafield in metafields
                       join objProperty in objProperties
                         on metafield.Name equals objProperty.Name
                       from att in metafield.GetCustomAttributes(false).OfType<ValidationAttribute>()
                       where !att.IsValid(objProperty.GetValue(entity))
                       select att.FormatErrorMessage(string.Empty)).ToList();
            if (results.Count() > 0)
            {
                return false;
            }
            else return true;
        }

        public static string IsCheckOutByAnotherUser(this EntityObject entity)
        {
            IObjectContext pharmacyContext = ObjectContextFactory.CreatePharmacyContext(Global.UserName, Global.CurrentConnectionString);
            PessimisticLocking pLock = new PessimisticLocking(pharmacyContext);
            return pLock.IsCheckOutByAnotherUser(entity);
        }
    }
}
